package com.hecj.common.lib.util;

import java.io.FileInputStream;
import java.util.Enumeration;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author hecj
 */
public class PropertyUtils {

    private static Logger logger = LoggerFactory.getLogger(PropertyUtils.class);

    private static final String DYNAMIC_CONFIG = "application.properties";

    protected Properties prop;

    private static PropertyUtils instance = new PropertyUtils();

    protected boolean started;

    protected PropertyUtils() {
        load();
    }

    public static PropertyUtils getInstance() {
        return instance;
    }

    /**
     * 被配置为异步定时任务
     */
    public void refresh() {
        if (started) {
            load();
        }
    }

    public void load() {
        try {
            if (prop == null) {
                prop = new Properties();
            }
            String path = this.getClass().getResource("/" + DYNAMIC_CONFIG).getPath();
            prop.load(new FileInputStream(path));
            started = true;
        } catch (Exception e) {
            logger.error("加载动态配置文件时异常", e);
        }
    }

    public String getProperty(String key, String defaultValue) {
        return prop.getProperty(key, defaultValue);
    }

    public String getProperty(String key) {
        return prop.getProperty(key);
    }


    public Enumeration keys() {
        return prop.keys();
    }
}

